<!--
 * @Author: Chuckie
 * @Email: chuckie@aliyun.com
 * @Date: 2022-11-10 14:35:49
 * @LastEditTime: 2022-11-12 14:32:09
 * @Description: 
 * @FilePath: /zl-web/src/views/basic/enterprise/detail.vue
 *  
-->
<template>
  <div class="app-container">
    <div>
      <el-checkbox v-for="(value,key,index) in state.dictRole" v-model="state.checkedRole[key]"  :label="state.dictRole[key]" size="large" />
    </div>
    <el-form :model="state.form" label-width="120px">
 

      <el-form-item>
        <el-button type="primary" @click="onSubmit">{{$t('common.button.save')}}</el-button>
        <el-button @click="onCancel">{{$t('common.button.back')}}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { create, selectOne, update ,add,selectRoleIdByUserId} from './api/base-user'
import { select as roleSelect} from './api/base-role'
const route = useRoute()
const router = useRouter()

const { proxy }: any = getCurrentInstance()
const state = reactive({
  form: {
    id: "",
    username: "",
    email: "",
    phone: "",
    sex: "",
    age: "",
    status: "",
    createBy: "",
    modifyBy: "",
    gmtCreate: "",
    gmtModify: "",
    lastLoginTime: "",
    nickname: "",
  },
dictRole:{},
checkedRole: {}
})

const onCancel = () => {
  router.back()
}

const onSubmit = async () => {
  if (route.params.id) {
    console.log(state.checkedRole)
    const data = await add({roleIds:Object.keys(state.checkedRole),userId:route.params.id})
    proxy.$message({ message: proxy.$t('common.message.editSuccessfully'), type: 'success' })
  } else {
    const data = await create(state.form)
    proxy.$message({ message: proxy.$t('common.message.saveSuccessfully'), type: 'success' })
    state.form.id = "";
    state.form.username = "";
    state.form.email = "";
    state.form.phone = "";
    state.form.sex = "";
    state.form.age = "";
    state.form.status = "";
    state.form.createBy = "";
    state.form.modifyBy = "";
    state.form.gmtCreate = "";
    state.form.gmtModify = "";
    state.form.lastLoginTime = "";
    state.form.nickname = "";
  }
}

const onSelectOne = async (id: string) => {
  const data = await selectOne(id)
  state.form = { ...data.data }
}
const onSelectRole = async ( ) => {
  const data = await roleSelect({pageNum:1,pageSize:1000})
  data.data.items.forEach(item=>{
    state.dictRole[item.id] = item.roleName
    
  })
}
// 通过userId 查询roleids 更新到 state.checkedRole 
const onSelectRoleByUserId = async (id:string |string[]) => {
  const data = await selectRoleIdByUserId(id)
  data.data.forEach(item=>state.checkedRole[item.id] = true)
}
 

 



onMounted(() => {
  onSelectRole()
  route.params.id && !Array.isArray(route.params.id) && onSelectOne(route.params.id)
  onSelectRoleByUserId(route.params.id)
})

</script>

<style lang="scss" scoped>
.el-input {
  width: 300px;
}

.el-select {
  width: 300px;
}

.el-textarea {
  width: 300px;
}
</style>
